package com.shujia.spark.core

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD

object Demo10ReduceByKey {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("groupByKey")
    val sc = new SparkContext(conf)

    val linesRDD: RDD[String] = sc.textFile("data/students.txt")

    //转换成kvRDD
    val kvRDD: RDD[(String, Int)] = linesRDD.map(line => {
      val clazz: String = line.split(",").last
      (clazz, 1)
    })

    /**
     * reduceByKey: 对相同的key的value做聚合计算
     * x,y=> x+y: 聚合函数再每一个组内会执行n-1次
     */

    val countRDD: RDD[(String, Int)] = kvRDD.reduceByKey((x, y) => {
      println(s"x=$x + y=$y = ${x + y}")
      x + y
    })

    countRDD.foreach(println)


    //使用groupByKey统计班级的人数
    val groupByKey: RDD[(String, Iterable[Int])] = kvRDD.groupByKey()
    val groupByKeyCountRDD: RDD[(String, Int)] = groupByKey.map {
      case (clazz: String, iter: Iterable[Int]) =>
        val num: Int = iter.sum
        (clazz, num)
    }

    groupByKeyCountRDD.foreach(println)

    while (true) {}
  }
}
